/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.easing.filters
{
	import com.qb9.flashlib.easing.Tween;
	import com.qb9.flashlib.lang.filter;
	import com.qb9.flashlib.utils.ClassUtil;
	
	import flash.display.DisplayObject;
	import flash.filters.BitmapFilter;

	internal class BaseFilterTween extends Tween
	{
		protected var bitmapFilter:BitmapFilter;
		protected var object:DisplayObject;
		
		private var filterName:String;
		
		public function BaseFilterTween(bitmapFilter:BitmapFilter, obj:DisplayObject, duration:int, dest:Object, options:Object=null)
		{
			filterName = ClassUtil.getFullName(bitmapFilter);
			
			this.object = obj;
			this.bitmapFilter = bitmapFilter;
			
			super(null, duration, dest, options);
		}
		
		override public function start():void
		{
			// Find a loitering filter
			for each (var f:BitmapFilter in object.filters)
				if (isOwnFilter(f))
					bitmapFilter = f; 
			
			// Copy custom attributes from the options
			for (var key:String in options)
				if (key in bitmapFilter)
					bitmapFilter[key] = options[key];
			
			this.obj = bitmapFilter;
			super.start();
		}
		
		// Flash clones BitmapFilters internally, so our instance gets lost
		private function isOwnFilter(filter:BitmapFilter):Boolean
		{
			return ClassUtil.getFullName(filter) === filterName;
		}
		
		private function isDifferentFilter(filter:BitmapFilter):Boolean
		{
			return !isOwnFilter(filter);
		}
		
		override protected function updateFunction(tween:Number):void
		{
			super.updateFunction(tween);
			
			object.filters = cleanFilters.concat(bitmapFilter);
		}

		private function get cleanFilters():Array
		{
			return filter(object.filters, isDifferentFilter);
		}
		
		override public function dispose():void
		{
			if (options && options.clean)
				object.filters = cleanFilters;
			
			bitmapFilter = null;
			object = null;
			super.dispose();
		}
	}
}